package com.itheima.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.LoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Override
    public PageResult<Emp> pageEmp(EmpQueryParam Param) {
        Page<Emp> page = new Page<>(Param.getPage(), Param.getPageSize());
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(Param.getName()), Emp::getName, Param.getName());
        queryWrapper.eq(Param.getGender() != null, Emp::getGender, Param.getGender());
        queryWrapper.between(Param.getBegin() != null && Param.getEnd() != null, Emp::getEntryDate, Param.getBegin(), Param.getEnd());
        Page<Emp> finalPage = page(page, queryWrapper);

        List<Emp> emplist = finalPage.getRecords();
        emplist.forEach((emp) -> {
            if (emp != null) {
                Dept dept = deptMapper.selectById(emp.getDeptId());
                if (dept != null) {
                    emp.setDeptName(dept.getName());
                }
            }
        });
        PageResult pageResult = new PageResult(finalPage.getTotal(), finalPage.getRecords());
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmpAndExpr(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        this.save(emp);
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList.size() > 0 && exprList != null) {
            exprList.forEach((empExpr) -> {
                if (empExpr != null) {
                    Integer id = emp.getId();
                    empExpr.setEmpId(id);
                }
            });
        }
        empExprMapper.insert(exprList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmpAndExprById(List<Integer> ids) {
        this.removeBatchByIds(ids);
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EmpExpr::getEmpId, ids);
        empExprMapper.delete(queryWrapper);
    }

    @Override
    public void updateEmpAndExpr(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmpExpr::getEmpId, emp.getId());
        empExprMapper.delete(queryWrapper);

        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach((expr) -> {
            Integer id = emp.getId();
            expr.setEmpId(id);
        });
        empExprMapper.insert(exprList);
    }

    @Override
    public Emp getEmpAndExprById(Integer id) {
        Emp emp = this.getById(id);
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmpExpr::getEmpId, emp.getId());
        List<EmpExpr> exprList = empExprMapper.selectList(queryWrapper);
        emp.setExprList(exprList);
        return emp;
    }


    @Override
    public JobOption empCount() {
        JobOption jobOption = new JobOption();
        List<Map> empList = empMapper.empCount();
        List<String> jobNameList = new ArrayList<>();
        List<Object> dataList = new ArrayList<>();

        for (Map map : empList) {
            jobNameList.add((String) map.get("jobName"));
            dataList.add(map.get("nums"));
        }
        jobOption.setJobList(jobNameList);
        jobOption.setDataList(dataList);
        return jobOption;
    }

    @Override
    public List<Map> genderCount() {
        List<Map> mapList = empMapper.genderCount();
        log.info("员工信息统计");
        return mapList;
    }


    @Override
    public List<String> selectImage() {
        List<String> list = empMapper.selectImage();
        return list;
    }

    @Override
    public LoginInfo login(EmpDto empDto) {
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Emp::getUsername, empDto.getUsername());
        queryWrapper.eq(Emp::getPassword, empDto.getPassword());
        Emp emp = empMapper.selectOne(queryWrapper);

        if (emp == null) {
            throw new LoginException("用户名或密码错误");
        }
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId(emp.getId());
        loginInfo.setName(emp.getName());
        loginInfo.setUsername(emp.getUsername());
        Map map = new HashMap();
        map.put("userId", emp.getId());
        map.put("username", emp.getUsername());
        String token = JwtUtils.generateJwt(map);
        loginInfo.setToken(token);
        return loginInfo;
    }

}
